package com.example.sixtrainingdemo.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.sixtrainingdemo.base.WeakRefHandler;
import com.example.sixtrainingdemo.contract.MineContract;
import com.example.sixtrainingdemo.entity.User;

public class MinePresenter implements MineContract.IMinePresenter {

    private static final int WHAT_GET_LOGIN_USER = 0;
    private MineContract.IMineView mMineView;
    private Context mContext;

    public MinePresenter(MineContract.IMineView mineView, Context context) {
        mMineView = mineView;
        mContext = context;
    }

    @Override
    public void getLoginUser(int id) {
        new Thread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                Uri uri = Uri.parse("content://com.example.sixtrainingdemo.provider/user");
                uri = uri.buildUpon().appendPath(id+"").build();
                Log.d("uri", uri.toString());
                Cursor cursor = mContext.getContentResolver().query(
                        uri, null, null, null);
                Log.d("cursor", "cursor.getCount() ===== "  + cursor.getCount());
                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        User user = new User();
                        user.setUserName(cursor.getString(cursor.getColumnIndex("user_name")));
                        user.setUserPassword(cursor.getString(cursor.getColumnIndex("user_password")));
                        Message message = Message.obtain();
                        message.obj = user;
                        message.what = WHAT_GET_LOGIN_USER;
                        mHandler.sendMessage(message);
                    }
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
        }).start();
    }

    Handler mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case WHAT_GET_LOGIN_USER:
                    mMineView.showUserInfo((User) msg.obj);
                    break;
            }
            return false;
        }
    });
}
